import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/bean/delay_data_entity.dart';
import 'package:jyofservice/bean/diao_du_list_entity.dart';
import 'package:jyofservice/generated/json/base/json_convert_content.dart';
import 'package:jyofservice/gongdandiaodu/DiaoDuDetail.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DelayPage extends StatefulWidget {
  @override
  _DelayPageState createState() => _DelayPageState();
}

class _DelayPageState extends State<DelayPage> {
  bool isloading = false;
  Color colorprimaryb = Colors.blue;
  Color colormiddleb = Color.fromRGBO(188, 223, 251, 1);
  Color colorprimaryt = Colors.white;
  Color colormiddlet = Colors.blue;
  List<DelayDataData?> list = [];
  int page = 1;
  TextEditingController ideaController = TextEditingController();
  ScrollController scrollController = ScrollController();
  int listtype=0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getJiashouData();

    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        page++;
        getJiashouData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(WebConfig().ColorValue),
      appBar: AppBar(
        centerTitle: true,
        title: Text(
            '退回审批', //FluroConvertUtils.fluroCnParamsDecode(widget.title),
            style: TextStyle(
                color: Colors.white, fontSize: ScreenUtil().setSp(45))),
      ),
      body: Stack(
        children: <Widget>[
          Column(
            children: <Widget>[
              SizedBox(
                height: ScreenUtil().setHeight(1),
                child: Container(),
              ),
              topButton(),
              SizedBox(
                height: ScreenUtil().setHeight(1),
                child: Container(),
              ),
              Expanded(
                  child: RefreshIndicator(
                child: ListView.builder(
                    controller: scrollController,
                    itemCount: list.length,
                    itemBuilder: (context, item) {
                      return listitem(context, item);
                    }),
                onRefresh: _refresh,
              )),
            ],
          ),
          Offstage(
            offstage: isloading,
            child: SpinKitFadingCircle(
              color: Colors.blue,
              size: 50.0,
            ),
          )
        ],
      ),
    );
  }

  Future _refresh() async {
    page = 1;
    list.clear();
    getJiashouData();
  }

  Widget topButton() {
    return Container(
      width: ScreenUtil().screenWidth,
      height: ScreenUtil().setHeight(80),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: GestureDetector(
                onTap: () {
                  colorprimaryb = Colors.blue;
                  colorprimaryt = Colors.white;
                  colormiddleb = Color.fromRGBO(188, 223, 251, 1);
                  colormiddlet = Colors.blue;
                  page = 1;
                  listtype=0;
                  list.clear();
                  getJiashouData();
                  if (mounted) {
                    setState(() {});
                  }
                },
                child: Container(
                  color: colorprimaryb,
                  child: Center(
                    child: Text(
                      "待复核",
                      style: TextStyle(
                          color: colorprimaryt,
                          fontSize: ScreenUtil().setSp(35)),
                    ),
                  ),
                ),
              )),
          Container(
            width: ScreenUtil().setHeight(2),
            color: Colors.white,
          ),
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                colormiddleb = Colors.blue;
                colormiddlet = Colors.white;
                colorprimaryb = Color.fromRGBO(188, 223, 251, 1);
                colorprimaryt = Colors.blue;
                page = 1;
                listtype = 1;
                list.clear();
                getJiashouData();
                if (mounted) {
                  setState(() {});
                }
              },
              child: Container(
                color: colormiddleb,
                child: Center(
                  child: Text(
                    "已复核",
                    style: TextStyle(
                        color: colormiddlet, fontSize: ScreenUtil().setSp(35)),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget listitem(BuildContext context, int i) {

    return InkWell(
      onTap: () {
        Navigator.push(context, new MaterialPageRoute(builder: (context) {
          return DiaoDuDetail(
            LSH: list[i]!.lSH,
            is0ffstage: true,
            view: "",
            isDeliver: false,
          );
        }));
      },
      child: Container(
        margin: EdgeInsets.fromLTRB(10, 5, 10, 5),
        padding: EdgeInsets.fromLTRB(10, 0, 10, 5),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black12,
              blurRadius: 5.0,
            ),
          ],
          borderRadius: BorderRadius.circular(10),
        ),
        child:  Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        "images/person.png",
                        width: ScreenUtil().setWidth(70),
                      ),
                      Expanded(
                        flex: 1,
                        child: ListTile(
                            title: Text(
                              list[i]!.rUserName ?? "",
                            ),
                            subtitle: Text(
                              list[i]!.createDate ?? "",
                            )),
                      ),
                      Text(
                        list[i]!.sHStateName!,
                        style: TextStyle(
                            color: list[i]!.state==1?Colors.red:Colors.green, fontSize: ScreenUtil().setSp(30)),
                      )
                    ],
                  ),
                  Container(
                    color: Colors.black26,
                    height: ScreenUtil().setHeight(1),
                  ),
                  SizedBox(
                    height: ScreenUtil().setHeight(10),
                  ),
                  Text(
                      list[i]!.reason == null
                          ? ""
                          : "退回原因：" + list[i]!.reason! ?? "",
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize: ScreenUtil().setSp(30))),
                  SizedBox(
                    height: ScreenUtil().setHeight(10),
                  ),
                  Text(
                      list[i]!.typeName == null
                          ? ""
                          : "工单类型：" + list[i]!.typeName.toString() ?? "",
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize: ScreenUtil().setSp(30))),
                  SizedBox(
                    height: ScreenUtil().setHeight(10),
                  ),
                  Offstage(
                    offstage: listtype == 1 ? true : false,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Container(),
                        ),
                        GestureDetector(
                          onTap: () {
                            //退回
                            showAlert("确定驳回该工单吗？", 0, list[i]!.iD.toString(), list[i]!.lSH);
                          },
                          child: Image.asset(
                            'images/disagree.png',
                            width: ScreenUtil().setWidth(150),
                            height: ScreenUtil().setHeight(50),
                          ),
                        ),
                        SizedBox(
                          width: ScreenUtil().setWidth(20),
                        ),
                        GestureDetector(
                          onTap: () {
                            showAlert("确定通过该工单吗？", 1, list[i]!.iD.toString(), list[i]!.lSH);
                          },
                          child: Image.asset(
                            'images/agree.png',
                            width: ScreenUtil().setWidth(150),
                            height: ScreenUtil().setHeight(60),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),

      ),
    );
  }

  void showAlert(String msg, int flag, String id, String? lsh) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text(msg),
            content: Container(
              height: ScreenUtil().setHeight(120),
              child: TextField(
                controller: ideaController,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(28),
                  //字母间距
                  letterSpacing: 0.5,
                  color: const Color(0xFF4A4A4A),
                ),
                decoration: InputDecoration(
                  hintStyle: TextStyle(
                      color: Colors.black54,
                      fontSize: ScreenUtil().setSp(28.0)),
                  hintText: "请输入审批意见",
                ),
              ),
            ),
            actions: <Widget>[
              new TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                    dealJiashou(flag, id, lsh);
                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
        });
  }

  Future dealJiashou(int flag, String id, String? lsh) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }

    try {
      SharedPreferences sharedPreferences =
      await SharedPreferences.getInstance();
      String? key = sharedPreferences.getString("key");
      String aesData = await (AesUtil.encodeBase64());
      var data;
      String url;
      if(flag==1) {
        data = {
          "key": key,
          "ClientType": "phone",
          "ClientKey": aesData,
          "ids":id,
          "LSH":lsh
        };
        url = "Work/AgreeGDHBRequest";

      }else{
        data = {
          "key": key,
          "ClientType": "phone",
          "ClientKey": aesData,
          "ids":id,
          "LSH":lsh,
          "Reason":ideaController.text.toString()
        };
        url ="Work/NoAgreeGDHBRequest";

      }



      Response response = await Dio().post(
          WebConfig().baseUrl + url,
          data: data);
      print("审批："+response.data.toString());

      if (response.data["Code"] == "200") {
        Fluttertoast.showToast(msg: "操作成功");
        _refresh();
      } else {
        Fluttertoast.showToast(msg: response.data["Msg"]);
      }
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getJiashouData() async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }

    try {
      SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      String? key = sharedPreferences.getString("key");
      String aesData = await (AesUtil.encodeBase64());
      var data = {
        "key": key,
        "view": 'GetMyDepartmentGDHuanBanRequest',
        "wherestr": listtype==0?"State in (1)":"State in (2,3)",
        "limit": 10,
        "page": page,
        "sortName": "CreateDate",
        "sortOrder": "desc",
        "ClientType": "phone",
        "ClientKey": aesData
      };
      print(data.toString());

      Response response = await Dio().post(
         WebConfig().baseUrl + "DB/postrowdataforlayui",
          data: data);
      print("审批："+response.data.toString());

      if (response.data["code"] == 0) {
        DelayDataEntity? dataEntity = DelayDataEntity().fromJson(response.data);
        if(dataEntity?.data != null){
          for (int i = 0; i < dataEntity!.data!.length; i++) {
            list.add(dataEntity.data![i]);
          }

        }

      } else {
        Fluttertoast.showToast(msg: response.data["Msg"]);
      }
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }
}
